<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 观点函数库
 * 
 * @desc 
 * @version 1.0.0 
 * @author  Jason
 * @date	2017年7月6日 下午6:22:16
 */
class Lib_opinion extends Lib_database
{
	/** @var Mod_opinion */
	private $mod_opinion = null;
	
	use libraries\common\DatabaseCURD;
	
	use libraries\common\CheckingStatus;
	
	use libraries\common\ConditionParser;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->CI->config->load('enumeration');
		
		$this->CI->load->model('mod_opinion');
		$this->mod_opinion =& $this->CI->mod_opinion;
		
		$this->set_render_config();
	}
	
	private function set_render_config()
	{
		$foreign_keys = [
				'master' => [
						['source_id', ['name'], $this->CI->mod_member, 'master', 'id'],
						['source_id', ['nickname'], $this->CI->mod_member, 'info', 'id'],
				],
		];
		$time_fields = [
				'master' => [
						['create_time', 'Y-m-d H:i:s'],
				],
		];
		$encode_fields = [
				'master' => [
						['images', 'implode'],
				],
		];
		$this->foreign_keys = $foreign_keys;
		$this->time_fields = $time_fields;
		$this->encode_fields = $encode_fields;
	}
	

	public function get_opinion_detail($id)
	{
		$item = $this->mod_opinion->select_instance_by_id($id);
		$item = $this->render_list($item, 'master', true, [
				[$this, 'parse_opinion_item'],
		]);
		return $item;
	}
	
	/**
	 * 获取观点列表
	 * 
	 * @desc    直取数据库记录
	 * @author  Jason
	 * @date	2017年7月7日 下午3:46:09
	 * 
	 * @param   
	 * 
	 * @return  array
	 */
	public function get_opinions_list($conditions, $page = 1, $number = 12)
	{
		$data = $this->mod_opinion->get_list($conditions, $page, $number);
		$data['data'] = $this->render_list($data['data'], 'master', false, [
				[$this, 'parse_opinion_item'],
		]);
		return $data;
	}
	
	public function parse_opinion_item($item)
	{
		$mapper_metrix = $this->CI->config->item('mapper_metrix')['opinion']['master'];
		
		$item['resource_type_text'] = @$mapper_metrix['resource_type'][$item['resource_type']];
		$item['source_type_text'] = @$mapper_metrix['source_type'][$item['source_type']];
		$item['target_type_text'] = @$mapper_metrix['target_type'][$item['target_type']];
		
		$item['status_tags'] = $this->mod_opinion->calculate_status_tags($item['status']);
		$item['status_tags'] = $this->filter_checking_status($item['status_tags']);
		return $item;
	}
	
	/**
	 * 获取主观点列表 - 订单评价打分
	 *
	 * @desc    重组过的数据
	 * @author  Jason
	 * @date	2017年7月7日 下午3:46:09
	 *
	 * @param
	 *
	 * @return  array
	 */
	public function get_master_opinions_list_for_routeOrderComment($conditions, $page = 1, $number = 12)
	{
		$conditions[] = ['where', [[
				'master_id' => NULL,
				'resource_type' => 'routeOrderComment',
				'target_type' => 'masterCommentContent'
		]]];
		$data = $this->mod_opinion->get_list($conditions, $page, $number);
		$data['data'] = $this->render_list($data['data'], 'master', false, [
				[$this, 'parse_opinion_item'],
		]);
		return $data;
	}
	
	/**
	 * 往主观点列表中追加从观点组件
	 * 
	 * @param array $master_list	主观点列表
	 * @param array $target_types	从观点的目标类型，如果为空则取配置全集
	 * 
	 * @return array with slaves
	 */
	public function append_component_for_master_list($master_list, $target_types = [])
	{
		if (empty($target_types)) {
			$target_types = $this->CI->config->item('other')['opinion']['route_order_comment']['slave_target_types'];
		}
		$master_ids = array_column($master_list, 'id');
		
		$conditions = [
				['select', 'id, master_id, target_type, target_id, score'],
				['where_in', ['master_id', $master_ids]],
				['where_in', ['target_type', $target_types]],
		];
		$components = $this->mod_opinion->select_instances_by_conditions($conditions);
		$this->CI->load->library('lib_tag');$lib_tag = $this->CI->lib_tag;$lib_tag instanceof Lib_tag;
		$components = $lib_tag->append_relations_for_resource_list($components, 'opinion');
		
		$componentDict = [];
		foreach ($components as $component) {
			$componentDict[$component['master_id']][$component['target_type']] = $component;
		}
		
		foreach ($master_list as &$master) {
			$slaves = isset($componentDict[$master['id']]) ? $componentDict[$master['id']] : [];
			$slaves = array_merge(array_fill_keys($target_types, null), $slaves);
			$master['slaves'] = $slaves;
		}
		unset($master);
		
		return $master_list;
	}
	
	/**
	 * 指定ID的主观点是否已经存在
	 *
	 * @desc	适用场景：在管理后台添加观点时指定主观点ID，这个主观点是需要存在的！
	 * @date	2017年7月7日 下午4:46:44
	 *
	 * @param number $master_id
	 *
	 * @return boolean
	 */
	public function has_opinion_exists($master_id)
	{
		if (empty($master_id)) {
			return true;
		}
		$selected_id = $this->mod_opinion->select_fields_by_id($master_id, ['id']);
		return !empty($selected_id);
	}
	
	/**
	 * 是否是支持的枚举值
	 *
	 * @date	2017年7月6日 下午6:39:44
	 *
	 * @param string $enum	枚举值
	 * @param string $field	枚举类型
	 *
	 * @return boolean
	 */
	private function is_supported_enum_in_field($enum, $field)
	{
		$mapper_metrix = $this->CI->config->item('mapper_metrix')['opinion']['master'];
		return array_key_exists($enum, $mapper_metrix[$field]);
	}
	public function is_supported_resource_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	public function is_supported_source_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	public function is_supported_target_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	
	/**
	 * 观点状态切换
	 * 
	 * @desc	启用禁用、是否审核（完毕）、是否审核通过、是否置顶
	 * @author  Jason
	 * @date	2017年6月20日 下午7:07:45
	 *
	 * @param number $id
	 * @param string $positiveTag eg: 'enabled'
	 *
	 * @return [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, ['nowTag' => 'enabled']]
	 * 				[true, ['nowTag' => 'disabled']]
	 * 				[false, ['error']]
	 */
	public function toggle_status_positive_tag()
	{
		$this->CI->load->library('form_validation');
		
		$status = false;
		$content = [];
		if(FALSE === $this->CI->form_validation->run("toggle_status_positive_tag_for_opinion")) {
			$errorKey = $this->CI->form_validation->error_array();
			$status = false;
			$content = $errorKey;
		} else {
			$id = $this->CI->input->post('id');
			$positiveTag = $this->CI->input->post('tag');
			
			$status = true;
			$ultimateTag = $this->mod_opinion->toggle_status_by_tag($id, $positiveTag);
			$content = ['nowTag' => $ultimateTag];
		}
		
		return [$status, $content];
	}
	
	/**
	 * 一步到位，创建添加路线订单评论
	 * 
	 * @author	Jason
	 * @date	2017年7月10日 下午3:17:17
	 * 
	 * @param array		$related_ids	相关ID，一维数组，包括resource_id、member_id、touroute_id、merchant_id、guide_id、designer_id、experience_id
	 * @param array		$content		评论内容
	 * @param string	$images			评论上传多图图片
	 * @param array		$slave_info		从评信息。多维数组，每一维至少包括从目标ID，评分，标签三个键
	 * @param string	$language		语言标识
	 * 
	 * @return [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, ['id' => '??']]
	 * 				[false, ['error']]
	 */
	public function create_route_order_comment($related_ids, $content, $images, $slave_info, $language)
	{
		$weighted_avg_score = $this->calculate_weighted_average_score($slave_info);
		$common_data = [
				'resource_type'	=> 'routeOrderComment',
				'resource_id'	=> $related_ids['resource_id'],
				'source_type'	=> 'member',
				'source_id'		=> $related_ids['member_id'],
		];
		$master_data = [
				'master_id'		=> null,
				'target_type'	=> 'masterCommentContent',
				'target_id'		=> $related_ids['resource_id'],
				'score'			=> $weighted_avg_score,
				'content'		=> $content,
				'images'		=> $images,
		];
		$master_data = array_merge($common_data, $master_data);
		// print_r($master_data);
		list($status, $content) = $this->mod_opinion->create_instance($master_data);
		if (!$status) {
			return [status, $content];
		}
		$relation_tags = [];
		$master_id = $content['id'];
		foreach ($slave_info as $key => $value)
		{
			$target_type = "{$key}Score";
			$slave_data = array_merge($common_data, [
					'master_id'		=> $master_id,
					'target_type'	=> $target_type,
					'target_id'		=> $value['target_id'],
					'score'			=> $value['score'],
			]);
			// print_R($slave_data);
			list($status, $content) = $this->mod_opinion->create_instance($slave_data);
			if (!$status) {
				return [$status, $content];
			}
			// TODO 平均分，记录到对应实体 cumulative_score1234+= / total_count1234++
			if (in_array($key, ['merchantService'])) {
				$this->CI->load->library('lib_merchant');
				$this->CI->lib_merchant->cumulative_score($slave_data['target_id'], $slave_data['score']);
			}
			
			$slave_id = $content['id'];
			$tag_module = "opinion" . ucfirst($key);
			$relation_tags[] = [
					// tag
					'module' => $tag_module,
					'parent_id' => 0,
					'language' => $language,
					'names' => $value['tags'],
					// relation
					'source_type' => 'opinion',
					'source_id' => $slave_id,
					'source_group_id' => $master_id,
			];
		}
		
		// print_r($relation_tags);
		$this->CI->load->library('lib_tag');
		$this->lib_tag =& $this->CI->lib_tag;
		foreach ($relation_tags as $rtag) {
			foreach ($rtag['names'] as $name) {
				list($status, $content) = $this->lib_tag->set_relation_tag(
						$rtag['module'], $rtag['parent_id'], $rtag['language'], $name, 
						$rtag['source_type'], $rtag['source_id'], $rtag['source_group_id']);
				if (!$status) {
					return [$status, $content];
				}
			}
		}
		
		return [true, ['id' => $master_id]];
	}
	
	/**
	 * 计算加权平均评分
	 * 
	 * @author	Jason
	 * @date	2017年7月10日 下午1:15:56
	 * 
	 * @param array		$slave_info		从评信息。多维数组，每一维至少包括从评分这个键
	 *
	 * @return number
	 */
	public function calculate_weighted_average_score($slave_info)
	{
		$weight = $this->CI->config->item('other')['opinion']['route_order_comment']['score_weight'];
		$s = 0;
		$n = 0;
		foreach ($slave_info as $key => $value) {
			$s += $value['score'] * $weight[$key];
			$n += $weight[$key];
		}
		$score = $s / $n;
		return $score;
	}
	
}